package cn.iocoder.yudao.module.cmt.service.team;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.team.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.team.TeamMemberDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.team.TeamMemberMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class TeamMemberServiceImpl implements TeamMemberService {

    @Resource
    private TeamMemberMapper teamMemberMapper;

    @Override
    public Long createTeamMember(TeamMemberSaveReqVO createReqVO) {
        TeamMemberDO teamMember = BeanUtils.toBean(createReqVO, TeamMemberDO.class);
        teamMemberMapper.insert(teamMember);
        return teamMember.getId();
    }

    @Override
    public void updateTeamMember(TeamMemberSaveReqVO updateReqVO) {
        validateTeamMemberExists(updateReqVO.getId());
        TeamMemberDO updateObj = BeanUtils.toBean(updateReqVO, TeamMemberDO.class);
        teamMemberMapper.updateById(updateObj);
    }

    @Override
    public void deleteTeamMember(Long id) {
        validateTeamMemberExists(id);
        teamMemberMapper.deleteById(id);
    }

    private void validateTeamMemberExists(Long id) {
        if (teamMemberMapper.selectById(id) == null) {
            throw exception(TEAM_MEMBER_NOT_EXISTS);
        }
    }

    @Override
    public TeamMemberDO getTeamMember(Long id) {
        return teamMemberMapper.selectById(id);
    }

    @Override
    public PageResult<TeamMemberDO> getTeamMemberPage(TeamMemberPageReqVO pageReqVO) {
        return teamMemberMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTeamMemberListByIds(List<Long> ids) {
        ids.forEach(this::validateTeamMemberExists);
        teamMemberMapper.deleteBatchIds(ids);
    }

}
